﻿package org.tisn.qq.net;

import java.nio.ByteBuffer;

import org.tisn.qq.QQClient;
import org.tisn.qq.packets.ErrorPacket;
import org.tisn.qq.packets.InPacket;
import org.tisn.qq.packets.OutPacket;
import org.tisn.qq.packets.PacketHelper;
import org.tisn.qq.packets.PacketParseException;

/**
 * 缺省的连接策略实现
 *
 * @author luma
 */
public class ConnectionPolicy implements IConnectionPolicy {
	QQClient client;
	PacketHelper helper;
	String id;
	
	public ConnectionPolicy(QQClient client, String id) {
		this.client = client;
		this.id = id;
		helper = new PacketHelper();
	}
	
	public boolean relocate(ByteBuffer buf) {
		return helper.relocate(buf);
	}
	
	public ErrorPacket createErrorPacket(int errorCode, String portName) {
	    ErrorPacket packet = new ErrorPacket(errorCode, client.getUser());
	    packet.connectionId = portName;
	    return packet;
	}

	public void pushResend(OutPacket out, String portName) {
		client.addResendPacket(out, portName);
	}
	
	public void flush() {
		client.getConnectionPool().flush();
	}
	
	public void pushIn(InPacket in) {
		client.addIncomingPacket(in, id);
	}
	
	public InPacket parseIn(ByteBuffer buf, boolean debug) throws PacketParseException {
		return helper.parseIn(buf, client.getUser(), debug);
	}
	
	public void putSent(OutPacket packet) {
		helper.putSent(packet);
	}
	
	public boolean isReplied(OutPacket packet, boolean add) {
		return helper.isReplied(packet, add);
	}
	
	public OutPacket retrieveSent(InPacket in) {
		return helper.retrieveSent(in);
	}

	public String getConnectionId() {
		return id;
	}
}
